package cn.lyq.card.base

import androidx.lifecycle.*
import cn.lyq.card.data.model.ResponseInfo
import cn.lyq.card.data.repository.Repository
import cn.lyq.card.data.src.Result
import cn.lyq.card.global.SPKeyGlobal
import cn.lyq.card.ui.login.LoginActivity
import cn.lyq.card.ui.pwd.PwdForgetActivity
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.Utils
import com.google.gson.JsonSyntaxException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import retrofit2.HttpException


abstract class SimpleVM : AndroidViewModel(Utils.getApp()) {

    /**
     * 可以添加不同的仓库，比如网络正常时使用阿里平台数据，网络异常时使用数据库
     */
    protected val repository = Repository

    class Factory : ViewModelProvider.NewInstanceFactory() {

    }

    protected fun <T> simpleEmit(tip: String = "正在请求数据", block: suspend () -> ResponseInfo<T>) =
        liveData(Dispatchers.Main) {
            emit(Result.loading(tip))
            try {
                val data = block()
                if (data.isOk()) {
                    emit(Result.success(data.data))
                } else {
                    if (data.isExpired() || data.isTokenError()) {
                        gotoLogin()
                    } else {
                        emit(Result.error(data.msg))
                    }
                }
            } catch (e: Exception) {
                LogUtils.eTag("simpleEmit", e.toString())
                if (e is HttpException && (e.code() == 101 || e.code() == 403)) {
                    gotoLogin()
                } else if (e is JsonSyntaxException) {
                    emit(Result.error("数据出错了，请稍后再试"))
                } else if (e is HttpException) {
                    emit(Result.error(e.message ?: ""))
                }
            }
        }


    fun <T> simplePost(
        info: MutableLiveData<Result<T>>,
        loadingString: String = "正在获取数据",
        block: suspend () -> ResponseInfo<T>
    ) {
        viewModelScope.launch {
            info.postValue(Result.loading(loadingString))
            try {
                val response = block()
                when {
                    response.isOk() -> {
                        info.postValue(Result.success(response.data))
                    }
                    response.isExpired() || response.isTokenError() -> {
                        gotoLogin()
                    }
                    else -> {
                        info.postValue(Result.error(response.msg))
                    }
                }
            } catch (e: Exception) {
                LogUtils.eTag("simplePost", e.toString())
                if (e is HttpException && (e.code() == 101 || e.code() == 403)) {
                    gotoLogin()
                    info.postValue(Result.error("登陆异常"))
                } else if (e is JsonSyntaxException) {
                    info.postValue(Result.error("数据出错了，请稍后再试"))
                } else {
                    info.postValue(Result.error(e.message ?: "网络异常"))
                }
            }
        }
    }

    private fun gotoLogin() {
        val top = ActivityUtils.getTopActivity()
        SPUtils.getInstance().put(SPKeyGlobal.BASE.TOKEN, "")
        if (top !is LoginActivity && top !is PwdForgetActivity && top is BaseActivity) {
            LoginErrorFg().show(top)
        }
    }
}